package com.powernobug.servlet;

import com.powernobug.util.Constant;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

@WebServlet(value = "/parameter", loadOnStartup = 1)
public class ParameterServlet extends HttpServlet {
    @SneakyThrows
    @Override
    public void init() {
        // 利用生命周期初始化值
        Properties channlesProperties = new Properties();
        Properties pathProperties = new Properties();

        try(
                InputStreamReader channlesInputStreamReader = new InputStreamReader(
                        ParameterServlet.class.getClassLoader().getResourceAsStream("express-vendors.properties"), StandardCharsets.UTF_8
                );
                InputStreamReader pathInputStreamReader = new InputStreamReader(
                        ParameterServlet.class.getClassLoader().getResourceAsStream("paths.properties"), StandardCharsets.UTF_8
                )
        ) {
            channlesProperties.load(channlesInputStreamReader);
            pathProperties.load(pathInputStreamReader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 共享值 → ServletContext，将配置文件对象全局共享
        getServletContext().setAttribute(Constant.CHANNELS_CONF, channlesProperties);
        getServletContext().setAttribute(Constant.PIC_PATH, pathProperties.getProperty(Constant.PIC_PATH));
        getServletContext().setAttribute(Constant.ROOT_DEPLOY, pathProperties.getProperty(Constant.ROOT_DEPLOY));
    }
}
